
package com.gitee.jmash.rbac.utils;

import com.gitee.jmash.crypto.digests.MD5Util;
import com.gitee.jmash.crypto.digests.SHA1Util;
import com.gitee.jmash.crypto.digests.SM3Util;
import com.gitee.jmash.rbac.enums.PwdFormat;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;

/** 密码Hash. */
public class PwdHashUtil {

  /** 加密算法. */
  public static final String hashAlgorithmName = "SHA-256";
  /** 循环次数. */
  public static final int hashIterations = 16;

  /**
   * 密码加密.
   *
   * @param pwdFormat 密码格式.
   * @param password 密码.
   * @param pwdAlt 随机密钥.
   */
  public static String encrypt(PwdFormat pwdFormat, String password, String pwdAlt) {
    if (pwdFormat == null || PwdFormat.NONE.equals(pwdFormat)) {
      return password;
    }
    String sha256password = password;
    if (StringUtils.isNotEmpty(pwdAlt)) {
      password = password + pwdAlt;
    }

    switch (pwdFormat) {
      case SM3:
        return SM3Util.get().digest(password);
      case MD5:
        return MD5Util.get().digest(password);
      case SHA1:
        return SHA1Util.get().digest(password);
      case SHA256:
        return new SimpleHash(hashAlgorithmName, sha256password, pwdAlt, hashIterations).toString();
      default:
        break;
    }

    return password;
  }

}
